(function ($) {
    var WNM = function (element) {
        var elem = $(element);
        var obj = this;

        var Slider = function (element) {
            var elem = $(element);
            var obj = this;

            var images = new Array(); // Holds all the images available
            var currentindex; // Holds the current index of the image
            var timer; // Holds the timer that continues looping;

			var wrapped = false; // Holds the fact if the img tag is wrapped by a 'A' tag (a link)

			var opt;
			
			var defaults = {							// default items need to be extended
				navigation : {
					cssNormal: 'navItem',
					cssActive: 'navItem-active'
				}
			};
			
            this.Slider = function (options) {
			
				$.extend(true, defaults, options);
				
                // set the options
                opt = defaults;
				
                // Set the timer +1 sec for clearance
                opt.timer.delay = opt.timer.delay + 1000;

                // Load all the images
                loadImages();

                // Load the timer
                loadTimer();

                // Show navigation
                loadNavigation();

                // Set the first image
				loadStartImage();
            };

            var loadImages = function (container) {
                // Hide this div, we don't need to see it we only need the data
                $(opt.imageContainer).hide();

                // Loop through all the images
                $(opt.imageContainer + ' li').each(function (index) {
                    var oImage = {};
                    oImage.ImageUrl = $(this).find('img').attr('src');
                    oImage.Text1 = $(this).find('.text1').text();
                    oImage.Text2 = $(this).find('.text2').text();
					oImage.Link = {};
					oImage.Link.Link = $(this).find('a').attr('href');
					oImage.Link.Target = $(this).find('a').attr('target');
                    images.push(oImage);
                });
            };

            var loadTimer = function () {
                if (opt.timer.timer && images.size > 1)
                    timer = window.setInterval(nextImage, opt.timer.delay);
            };

            var loadNavigation = function () {
                // First check if we need to create the navigation
                if (opt.navigation.navigation) {
                    var nav = $(opt.navigation.container);
					
                    $.each(images, function (i, val) {
                        n = i + 1;
						
						// Do we need to load the custom item?
						if(opt.navigation.inline.navItem != undefined)
							nav.append('<li><a href="#" class="' + opt.navigation.cssNormal + '" ref="' + n + '">' + opt.navigation.inline.navItem + '</a></li>');
						else
							nav.append('<li><a href="#" class="' + opt.navigation.cssNormal + '" ref="' + n + '">' + n + '</a></li>');
                    });

                    if (opt.navigation.inline.inline) {
                        nav.prepend('<li><a href="#" class="prev"><img src="' + opt.navigation.inline.imagePrev + '" alt="prev" /></a></li>');
                        nav.append('<li><a href="#" class="next"><img src="' + opt.navigation.inline.imageNext + '" alt="next" /></a></li>');
                        
						$(nav).on("click", ".next", obj.next);
						$(nav).on("click", ".prev", obj.previous);
                    }
					
					$(nav).on("click", '.' + opt.navigation.cssNormal, obj.navChange);
                }
            };

			var loadStartImage = function() {
				if(opt.startindex >= 0 && opt.startindex <= images.length && opt.startindex != undefined)
					setImage(opt.startindex);
				else
					setImage(0);
			};

            var nextImage = function () {
                var n;
                if (currentindex + 1 > (images.length - 1))
                    n = 0;
                else
                    n = currentindex + 1;

                setImage(n);
            };

            var previousImage = function () {
                var n
                if (currentindex - 1 < 0)
                    n = images.length - 1;
                else
                    n = currentindex - 1;

                setImage(n);
            };
			
			var setActiveNavigation = function() {
				var c = $(opt.navigation.container);
				c.find('.' + opt.navigation.cssActive).removeClass(opt.navigation.cssActive).addClass(opt.navigation.cssNormal);
				c.find('a[ref="' + (currentindex + 1) + '"]').removeClass(opt.navigation.cssNormal).addClass(opt.navigation.cssActive);
			};

            this.navChange = function (data) {
				data.preventDefault();
                var n = $(data.currentTarget).attr('ref');
                resetTimer();
                setImage(n - 1);
            };

            this.next = function (event) {
				event.preventDefault();
                resetTimer();
                nextImage();
            };

            this.previous = function (event) {
				event.preventDefault();
                resetTimer();
                previousImage();
            };

            this.image = function (id) {
                setImage(id - 1);
                resetTimer();
            };

            var setImage = function (id) {
                setCurrentIndex(id); // We need to save this index
				
				// Set the image
				$(elem.selector).fadeOut(200,function(){
				  $(this).attr('src', images[currentindex].ImageUrl).fadeIn(600);
				});
				
				// Set active li item
				setActiveNavigation();
				
				// Set the link
				if(opt.link.link)
				{
					// Is the image already wrapped?
					if(!wrapped)
					{
						$(elem).wrap('<a href="'+ images[currentindex].Link.Link +'" id="'+ opt.link.container +'" target="'+images[currentindex].Link.Target+'"></a>');
						wrapped = true;
					}
					else
						if(images[currentindex].Link != undefined)
						{
							$('#' +opt.link.container).attr("href", images[currentindex].Link.Link);
							$('#' + opt.link.container).attr("target", images[currentindex].Link.Target);
						}	
						else
						{
							$(elem).unwrap();
							wrapped = false;
						}
					
				}
              
				// Set the text
				if(opt.text.text)
				{
				$(opt.text.container1).text(images[currentindex].Text1);
				$(opt.text.container2).text(images[currentindex].Text2);
				}
            };

            var setCurrentIndex = function (index) {
              if(opt.timer.random && opt.startindex == undefined)
                currentindex = randomImage();
              else
                currentindex = index;
            };

            var resetTimer = function () {
                if (timer) {
                    window.clearTimeout(timer);
                    loadTimer();
                }
            };
          
            var randomImage = function() {
				var r = Math.floor(Math.random()*images.length);
				if(r != currentindex)
					return r
				else
					return randomImage();
            };
        };

        this.Slider = function (options) {
			if(elem.length)
			{
				var slider = new Slider(elem);
				slider.Slider(options);
				return slider;
			}
			else
				return null;
        };
    };

    $.fn.WNMedia = function () {
        return wnm = new WNM(this);
    };
})(jQuery);
